package com.program.facesigninsystem.service.impl;

import com.alibaba.fastjson.JSON;
import com.program.facesigninsystem.dao.IUserInfoDao;
import com.program.facesigninsystem.entity.ResponseModel;
import com.program.facesigninsystem.util.GetInfoUtil;
import com.program.facesigninsystem.util.TokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @author Mapler
 */
@Service
public class ScanCodeLoginService {
    private IUserInfoDao iUserInfoDao;

    @Autowired
    public ScanCodeLoginService(IUserInfoDao iUserInfoDao) {
        this.iUserInfoDao = iUserInfoDao;
    }

    public ResponseModel getLoginCode(){
        String id = GetInfoUtil.getId();
        return new ResponseModel(200,"获取成功","xiangqian.club?sessionId="+id);
    }

    public ResponseModel scanCodeLogin(
            String sessionId,
            String uid,
            String lid,
            String state,
            String endTime,
            String actId,
            String title,
            String linkType,
            String className,
            String cid,
            String type,
            String ccid){
        Map<String,Object> userInfo = iUserInfoDao.selectU(uid);
        if (userInfo != null) {
            String token = TokenUtil.createToken(uid, "op82Q4iUHjAXTpRulfRXhKbYYLKE");
            iUserInfoDao.updateToken(uid,token);
            userInfo.put("lid",lid);
            userInfo.put("state",state);
            userInfo.put("endTime",endTime);
            userInfo.put("actId",actId);
            userInfo.put("title",title);
            userInfo.put("linkType",linkType);
            userInfo.put("className",className);
            userInfo.put("cid",cid);
            userInfo.put("type",type);
            userInfo.put("ccid",ccid);
            if(WebSocketServer.sendMessage(JSON.toJSON(userInfo).toString(),sessionId) == 0) {
                return new ResponseModel(200, "登录成功");
            }else {
                return new ResponseModel(132, "登录失败,未找到会话");
            }
        } else {
            return new ResponseModel(132, "登录失败");
        }
    }

    public ResponseModel waitConfirmation(String sessionId, String uid,String type){
        String avatar = iUserInfoDao.selectAvatar(uid);
        Map<String, String> map = new HashMap<>(1);
        map.put("avatar",avatar);
        map.put("type",type);
        if(WebSocketServer.sendMessage(JSON.toJSON(map).toString(),sessionId) == 0){
            return new ResponseModel(200, "扫码成功");
        }else {
            return new ResponseModel(132, "未找到会话");
        }
    }
}
